// 导入 Vue Router 相关模块
import {createRouter, createWebHistory} from 'vue-router'
import {useUserStore} from '@/stores/user'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Home from '@/views/Home.vue'
import Dashboard from '@/views/Dashboard.vue'
import UserManagement from '@/views/user/UserManagement.vue'
import RoleManagement from '@/views/user/RoleManagement.vue'
import Profile from '@/views/user/Profile.vue'
import Settings from '@/views/system/Settings.vue'

const routes = [
    {
        path: '/',
        redirect: '/home/dashboard'
    },
    {
        path: '/login',
        name: 'login',
        component: Login,
        meta: {requiresAuth: false}
    },
    {
        path: '/register',
        name: 'register',
        component: Register,
        meta: {requiresAuth: false}
    },
    {
        path: '/home',
        name: 'home',
        component: Home,
        redirect: '/home/dashboard',
        meta: {requiresAuth: true},
        children: [
            {
                path: 'dashboard',
                name: 'dashboard',
                component: Dashboard,
                meta: {title: '首页', requiresAuth: true}
            },
            {
                path: 'user/users_management',
                name: 'user-management',
                component: UserManagement,
                meta: {title: '用户管理', requiresAuth: true}
            },
            {
                path: 'user/roles_management',
                name: 'role-management',
                component: RoleManagement,
                meta: {title: '角色管理', requiresAuth: true}
            },
            {
                path: 'user/profile',
                name: 'profile',
                component: Profile,
                meta: {title: '个人中心', requiresAuth: true}
            },
            {
                path: 'system/settings',
                name: 'settings',
                component: Settings,
                meta: {title: '系统设置', requiresAuth: true}
            }
        ]
    },
    // 将未匹配的路由重定向到 404 页面
    {
        path: '/:pathMatch(.*)*',
        component: () => import('@/views/NotFound.vue'),
        meta: {requiresAuth: false}
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 每次路由变化时，从localStorage重新读取token（确保刷新页面时token不会丢失）
    const savedToken = localStorage.getItem('token')
    if (savedToken && !userStore.token) {
        userStore.token = savedToken
    }

    // 检查路由是否需要认证
    if (to.meta.requiresAuth) {
        // 检查用户是否已登录（基于localStorage中的token）
        if (!savedToken) {
            // 未登录，重定向到登录页面
            next({
                path: '/login',
                query: { redirect: to.fullPath } // 保存原始路径以便登录后重定向
            })
            return
        }

        // 有token，检查是否需要获取用户信息
        if (!userStore.user && savedToken) {
            try {
                console.log('路由守卫：尝试获取用户信息')
                await userStore.fetchUserInfo()
                console.log('路由守卫：获取用户信息成功')
                next()
            } catch (error: any) {
                console.error('路由守卫：获取用户信息失败:', error)

                // 只有在明确的401认证失败时才清除token
                // 网络错误或其他临时错误不应该导致token被删除
                if (error?.response?.status === 401) {
                    console.log('路由守卫：401认证失败，清除token')
                    userStore.clearAuth()
                    next({
                        path: '/login',
                        query: { redirect: to.fullPath }
                    })
                } else {
                    // 网络错误或其他错误，保留token，允许用户继续访问
                    console.log('路由守卫：网络错误或临时错误，保留token，允许访问')
                    next()
                }
            }
        } else {
            // 已有用户信息，直接允许访问
            next()
        }
    } else {
        // 不需要认证的路由

        // 如果用户已登录，访问登录或注册页面时重定向到首页
        if ((to.path === '/login' || to.path === '/register') && savedToken && userStore.user) {
            next('/home/dashboard')
        } else {
            next()
        }
    }
})

// 全局后置守卫：设置页面标题
router.afterEach((to) => {
    if (to.meta && to.meta.title) {
        document.title = `${to.meta.title} - 管理系统`
    } else {
        document.title = '管理系统'
    }
})

export default router
